<?php
namespace AppWeb\Controller;
use Think\Controller;
use Org\Wechats\Wechat;
class UserController extends Controller {
	public function wechatAuth(){
	   if(!empty(session('openid'))){
		  redirect('index');
	   }
	   else{
		    $wechat = new Wechat(jsapi());
			if(isset($_GET['code'] )){
				$opneidToken =$wechat->getOauthAccessToken();
				session('openid',$opneidToken['openid']);
				redirect('https://api.weibo.com/oauth2/authorize?&response_type=code&client_id=3856819567&redirect_uri=http://p1.junshenwx.com:8000/auth');
			}else{
				if(isset($_GET['id'])){
					$state=$_GET['id'].','.$_GET['openid'];
				}else{
					$state='';
				}
				$callback='http://'.$_SERVER['HTTP_HOST'].U('wechatAuth');
				$url=$wechat->getOauthRedirect($callback,$state,$scope='snsapi_userinfo');
				header('Location:'.$url);
		    }
	   }
		
	}
	public function wechatIs(){
	   if(!empty(session('openid'))){
		  redirect('index');
	   }
	   else{
		    $wechat = new Wechat(jsapi());
			if(isset($_GET['code'] )){
				$opneidToken =$wechat->getOauthAccessToken();
				session('openid',$opneidToken['openid']);
				redirect('https://api.instagram.com/oauth/authorize/?client_id=98b6258b3d434d31a95ab0eda750db04&redirect_uri=http://p1.junshenwx.com:8000/auth_instgram&response_type=code');
			}else{
				if(isset($_GET['id'])){
					$state=$_GET['id'].','.$_GET['openid'];
				}else{
					$state='';
				}
				$callback='http://'.$_SERVER['HTTP_HOST'].U('wechatAuth');
				$url=$wechat->getOauthRedirect($callback,$state,$scope='snsapi_userinfo');
				header('Location:'.$url);
		    }
	   }
		
	}
	
	
	
	public function index(){
		if(!empty(session('token'))){
		   $urls='https://api.weibo.com/2/statuses/friends_timeline.json?source=3856819567&access_token='.session('token').'&count=50&page=1&base_app=0';
		   $datas=json_decode(http_get($urls),TRUE);
           $this->assign('statuses',$datas["statuses"]);
		   $this->display();
		}
		if(!empty(session('inst_token'))){
			//$urli='https://api.instagram.com/v1/users/self/media/recent/?access_token='.session('inst_token');
		   //$datasi=json_decode(http_get($urli),TRUE);
          // $this->assign('datasi',$datasi['data']);
		  // dump($datasi->data);
		   $this->display();
		}
		if($_POST['text']){
			$url='https://api.weibo.com/2/statuses/update.json';
			$param = "access_token=".session('token')."&status=".urlencode($_POST['text']);
			https_request($url,$param);
			$this->display();
		}
		  
    }
	
    public function UserRegist(){
		if(empty($_GET)){
		  $this->assign('openid',session('openid'));
          $this->display();
		}else{
	     if(!empty($_GET['token'])){
		  $token=$_GET['token'];
		  session('token',$token);
		 }else if(!empty($_GET['inst_token'])){
			 $insd_token=$_GET['inst_token'];
			 session('inst_token',$insd_token);
			// dump(session('inst_token'));
		 }
		  
		  $this->display();
		}
    }
	public function me(){
		$this->display();
	}
	public function ceshi(){
		$this->redirect('UserRegist', array('openid' =>str_encrypt('nihaonihaonihao','E','nowamagic')), 1, '页面跳转中...');
	}
	public function UserForget(){
		$data= I("post.");
        if(!empty($data['sms_code']) and session('sms_code')==$data['sms_code']){
            $User = D("User"); 
			$field='phone,pass';
			$where['phone']=session('phone');
			$user_find=$User->user_find($where,$field); 
			if($user_find){
				 $this->assign('userfind',$user_find);
				 $this->display('UserPass');
			}
			else{
			    $this->error("发送失败！", 'index',5);	 
		    }
        }else{
            $this->display();
        }
    }
	public function UserUpdate(){
		  $User = D("User"); 
		  $data = I("post.");
	      $where['id'] = session('id');
		  if(!empty($data['pass'])){
			  $update_user=$User->user_update($where,$data);
			    if($update_user){
				  $this->success("修改成功", 'BankAdd',3);
				}
				else {
				  $this->error("密码与现有密码相同！", 'UserUpdate',10);
				}
		  }
		  else if(!empty($_FILES['img'])){
		       $files=$_FILES['img'];
		       $name_pic='/User/'.session('id');
			   $imgs['img']="/uploads".(img_upload($name_pic,$files));
			   $update_user=$User->user_update($where,$imgs);
			    if($update_user){
				    $this->success("修改成功", 'index',3);
				}
				else {
				    $this->error("图片上传有误！", 'UserUpdate',10);
				}
		  }
		  else{
			 $this->display();	
		  }
	}
	public function check() {
		  dump($_GET);
		  foreach ($list as $v=>$a) 
          { 
            echo $a['upid'] .'-'. $a['title']; 
          } 
    }
	public function SmsCheck() {
		    $smscode = I('get.smscode');
			$openid = I('get.openid');
			$incode = I('get.incode');
			if($smscode==session('sms_code') and !empty($openid)){
				$User = D("User"); 
		        $where['phone']= I('get.phone');
				$where['openid']= str_encrypt($openid,'D','junshen');
				$rules['name']= '注册';
				$fileq='credits';
				$ScoreRules = D("ScoreRules"); 
				$rules_selectt=$ScoreRules->rules_find($rules,$fileq);
				if($rules_selectt){
				    $score=$rules_selectt['credits'];
				    $where['score'] = $score;
					$user_add=$User->user_add($where); 
					if($user_add){
						$ScoreLog = D("ScoreLog"); 
						$score_log[] = array('uid'=>$user_add,'type'=>'注册','credits'=>$score,'time'=>time());
						if(!empty(I('get.incode'))){
							$score_log[] = array('uid'=>I('get.incode'),'type'=>'推荐','credits'=>200,'time'=>time());
							$whereup['id']=I('get.incode');
							$user_upe=$User->userscore_setInc($whereup,200);
						}
						if(!empty($score)){
						    $scorelog_add=$ScoreLog->scorelog_addALL($score_log);
						}
						else{
						   $scorelog_add=1;
						}
						if($scorelog_add){
						 session('phone',$where['phone']);	
						 session('id',$user_add);	
						 session('openid',$where['openid']);
						 echo 1;
						}
					}
					else{
				        echo "user_add";
				    }
				}else{
				   echo "rules_selectt";
				}
		    }
			else{
		      echo 0;
			}
		
	}
	public function BankAdd() {
	    if(!empty(session('phone'))and!empty(session('pass'))){
			  $User = D("User"); 
			  $data = I("post.");
			  if(!empty($data['branch'])){
				  $where['phone'] = session('phone');
				  $update_user=$User->user_update($where,$data);
				   if($update_user){
					  $this->redirect('BankCardAdd'); 
					}
					else {					  
					}
			  }
			  else{
				 $Branch = D("Branch"); 
				   $file='area';
				   $where='1';
				   $select_branch=$Branch->branch_select_group($file,$where);
				   $this->assign('selectbranch',$select_branch); 
				   $this->display();
			  }
		  }
		 else{
			  $this->error("您还未登录",U('Index/index'),1);
		 }
	}
	public function ChildAdd() {
		 if(!empty(session('phone'))and!empty(session('pass'))){ 
		    $User = D("User"); 
			$data = I("post.");
			if(!empty($data['name'])&&!empty($data['sex'])){
				$where['phone'] = session('phone');
				$datas['name']=$data['name'];
				$datas['sex']=$data['sex'];
				$datas['birth']=$data['birthy'].'-'.$data['birthm'].'-'.$data['birthd'];
				$update_user=$User->user_update($where,$datas);
				 if($update_user){
				    $this->redirect('index'); 
				  }
				  else {
					
				  }
			}
			else{
		       $this->display();
			}
		}
		 else{
			  
			  $this->error("您还未登录",U('Index/index'),1);
		 }		
	}
	public function verify_c(){  
		$Verify = new \Think\Verify();  
		$Verify->fontSize = 17;  
		$Verify->length   = 4;  
		$Verify->useNoise = false;  
		$Verify->codeSet = '0123456789';  
		$Verify->imageW = 130;  
		$Verify->imageH = 50;  
		//$Verify->expire = 600;  
		$Verify->entry();  
	}  
	public function UserCheng(){  
	    $this->display();
	}
	public function UserImg(){
	   $this->display();
	}
	public function ForgetPass(){
		if (IS_AJAX){
			$phone = I('get.phone');
			$dcode=rand_number($min=1, $max=99999);
			if(send_sms_code($phone,$dcode)){
			   session('sms_code',$dcode);
			   session('phone',$phone);
			   echo 1;
			}
		}
		else{
	        echo '非法载入';
		}
    }
	public function UserLogin(){
		$this->display();
	}
	public function str_encrypt($tex,$type,$key){
	  $chrArr=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
                  'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
                  '0','1','2','3','4','5','6','7','8','9');
	  if($type=="D"){
		  if(strlen($tex)<14)return false;
		  $verity_str=substr($tex, 0,8);
		  $tex=substr($tex, 8);
		  if($verity_str!=substr(md5($tex),0,8)){
			  //完整性验证失败
			  return false;
		  }    
	  }
	  $key_b=$type=="D"?substr($tex,0,6):$chrArr[rand()%62].$chrArr[rand()%62].$chrArr[rand()%62].$chrArr[rand()%62].$chrArr[rand()%62].$chrArr[rand()%62];
	  $rand_key=$key_b.$key;
	  $rand_key=md5($rand_key);
	  $tex=$type=="D"?base64_decode(substr($tex, 6)):$tex;
	  $texlen=strlen($tex);
	  $reslutstr="";
	  for($i=0;$i<$texlen;$i++){
		  $reslutstr.=$tex{$i}^$rand_key{$i%32};
	  }
	  if($type!="D"){
		  $reslutstr=trim($key_b.base64_encode($reslutstr),"==");
		  $reslutstr=substr(md5($reslutstr), 0,8).$reslutstr;
	  }
	  return $reslutstr;
  }
}